package main

import (
	"fmt"
	"math/rand"
	"time"
)

func msgGen(name string) chan string {
	c := make(chan string)
	go func() {
		i := 0

		for {
			randomWait := time.Duration(rand.Intn(1000)+500) * time.Millisecond
			time.Sleep(randomWait)
			c <- fmt.Sprintf("service %s: message %d", name, i)
			i++
		}
	}()
	return c
}

func faIn(c1, c2 chan string) chan string {
	c := make(chan string)
	go func() {
		for {
			c <- <-c1
		}
	}()
	go func() {
		for {
			c <- <-c2
		}
	}()
	return c
}

func faInRangeBad(chs ...chan string) chan string {
	c := make(chan string)
	for _, ch := range chs {
		go func() {
			for {
				c <- <-ch
			}
		}()
	}

	return c
}
func faInRangeSuccess(chs ...chan string) chan string {
	c := make(chan string)
	for _, ch := range chs {
		chCopy := ch
		go func() {
			for {
				c <- <-chCopy
			}
		}()
	}
	return c
}
func faInRangeSuccess2(chs ...chan string) chan string {
	c := make(chan string)
	for _, ch := range chs {
		go func(in chan string) {
			for {
				c <- <-in
			}
		}(ch)
	}
	return c
}
func faInBySelect(c1, c2 chan string) chan string {
	c := make(chan string)
	go func() {
		for {

			select {
			case m := <-c1:
				c <- m
			case m := <-c2:
				c <- m

			}
		}
	}()

	return c
}

func main() {
	gen := msgGen("service1")
	gen2 := msgGen("service2")

	m := faInRangeSuccess2(gen, gen2)
	for {
		fmt.Println(<-m)
	}
}
